<route lang="yaml">
  meta:
    title: 商品类别管理
  </route>

<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { reactive, ref } from 'vue'

interface ProductCategory {
  id: number
  label: string
  children?: ProductCategory[]
  parentId?: number
  status: '启用' | '停用'
}

// 树形数据
const tableData = ref<ProductCategory[]>([
  {
    id: 1,
    label: '电子产品',
    status: '启用',
    children: [
      { id: 11, label: '手机', parentId: 1, status: '启用' },
      { id: 12, label: '电脑', parentId: 1, status: '启用' },
    ],
  },
  {
    id: 2,
    label: '家居用品',
    status: '启用',
    children: [
      { id: 21, label: '家具', parentId: 2, status: '启用' },
      { id: 22, label: '灯具', parentId: 2, status: '停用' },
    ],
  },
])

// 弹窗控制
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit' | 'addChild'>('add')

// 表单引用
const formRef = ref<FormInstance>()

// 表单数据
const formData = reactive<Partial<ProductCategory>>({
  label: '',
  status: '启用',
  parentId: undefined,
})

// 验证规则
const rules = reactive({
  label: [{ required: true, message: '请输入类别名称', trigger: 'blur' }],
})

// 打开新增弹窗
function handleAdd() {
  dialogType.value = 'add'
  Object.assign(formData, {
    id: undefined,
    label: '',
    status: '启用',
    parentId: undefined,
  })
  dialogVisible.value = true
}

// 打开添加子类弹窗
function handleAddChild(row: ProductCategory) {
  dialogType.value = 'addChild'
  Object.assign(formData, {
    id: undefined,
    label: '',
    status: '启用',
    parentId: row.id,
  })
  dialogVisible.value = true
}

// 打开编辑弹窗
function handleEdit(row: ProductCategory) {
  dialogType.value = 'edit'
  Object.assign(formData, { ...row })
  dialogVisible.value = true
}

// 删除分类
async function handleDelete(row: ProductCategory) {
  try {
    await ElMessageBox.confirm(
      `确定删除分类【${row.label}】及其所有子类吗？`,
      '删除确认',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    deleteCategory(tableData.value, row.id)
    ElMessage.success('删除成功')
  }
  catch {
    // 取消删除
  }
}

// 递归删除分类
function deleteCategory(data: ProductCategory[], id: number): boolean {
  return data.some((item, index) => {
    if (item.id === id) {
      data.splice(index, 1)
      return true
    }
    if (item.children && deleteCategory(item.children, id)) {
      return true
    }
    return false
  })
}

// 提交表单
function submitForm() {
  formRef.value?.validate((valid) => {
    if (valid) {
      const newCategory: ProductCategory = {
        id: Date.now(),
        label: formData.label!,
        status: formData.status!,
        parentId: formData.parentId,
      }

      if (dialogType.value === 'edit') {
        updateCategory(tableData.value, formData.id!, newCategory)
      }
      else {
        addCategory(tableData.value, newCategory)
      }

      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'edit' ? '修改成功' : '新增成功')
    }
  })
}

// 递归添加分类
function addCategory(data: ProductCategory[], newCategory: ProductCategory): boolean {
  if (!newCategory.parentId) {
    data.push(newCategory)
    return true
  }

  return data.some((item) => {
    if (item.id === newCategory.parentId) {
      item.children = item.children || []
      item.children.push(newCategory)
      return true
    }
    if (item.children && addCategory(item.children, newCategory)) {
      return true
    }
    return false
  })
}

// 递归更新分类
function updateCategory(data: ProductCategory[], id: number, newData: ProductCategory): boolean {
  return data.some((item, index) => {
    if (item.id === id) {
      data[index] = { ...item, ...newData }
      return true
    }
    if (item.children && updateCategory(item.children, id, newData)) {
      return true
    }
    return false
  })
}

// 查找父级名称
function findParentName(id: number): string {
  const find = (data: ProductCategory[]): string => {
    for (const item of data) {
      // eslint-disable-next-line style/max-statements-per-line
      if (item.id === id) { return item.label }
      if (item.children) {
        const result = find(item.children)
        // eslint-disable-next-line style/max-statements-per-line
        if (result) { return result }
      }
    }
    return ''
  }
  return find(tableData.value)
}
</script>

<template>
  <div>
    <FaPageMain>
      <div class="mb-4 flex justify-between">
        <div class="button-group">
          <el-button type="primary" @click="handleAdd">
            <el-icon><Plus /></el-icon>
            <span class="ml-1">新增分类</span>
          </el-button>
        </div>
      </div>

      <div class="table-wrapper">
        <el-table
          :data="tableData"
          row-key="id"
          default-expand-all
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column prop="label" label="类别名称" />
          <el-table-column prop="status" label="状态" width="120">
            <template #default="{ row }">
              <el-tag :type="row.status === '启用' ? 'success' : 'danger'">
                {{ row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="260">
            <template #default="{ row }">
              <div class="flex items-center gap-2">
                <el-button type="primary" size="small" @click="handleAddChild(row)">
                  添加子类
                </el-button>

                <el-button type="primary" link @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                  <span class="ml-1">编辑</span>
                </el-button>
                <el-button type="danger" link class="ml-3" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  <span class="ml-1">删除</span>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </FaPageMain>

    <!-- 分类编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'edit' ? '编辑分类' : '新增分类'"
      width="500px"
    >
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item v-if="formData.parentId" label="父级分类">
          <el-input :value="findParentName(formData.parentId)" disabled />
        </el-form-item>

        <el-form-item label="分类名称" prop="label">
          <el-input v-model="formData.label" placeholder="请输入分类名称" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status">
            <el-option label="启用" value="启用" />
            <el-option label="停用" value="停用" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="submitForm">
          确认
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.table-wrapper {
  margin-top: 16px;
  border: 1px solid var(--el-border-color);
  border-radius: 4px;
}

:deep(.el-table .el-table__cell) {
  padding: 12px 0;
}
</style>
